import urllib.request
import requests
import json
import re
from bs4 import BeautifulSoup

# 请求头部
headers = {
    'origin': 'http://yidiankai.net',
    'referer': 'http://yidiankai.net/',
    'host': 'www.yidiankai.net',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4093.3 Safari/537.36'
}
# 超时时间
timeout = 8

'''
    远程请求
'''


def remote():
    values = {
        'username': '13177065854',
        'password': '065854'
    }

    # 参数编码
    data = urllib.parse.urlencode(values).encode('utf-8')

    # 请求地址
    baseUrl = 'http://www.yidiankai.net/api/user_jump/do_user_login'
    # 进入主页
    session = requests.Session()
    response = session.post(url=baseUrl, headers=headers, data=data, timeout=timeout)

    try:
        result_data = response.json()

        if result_data['status']:
            # 获取多少道题目
            exercise_success_page = session.get(
                'http://www.yidiankai.net/index/exam/lesson_sort/courseSetId/42/classroomId/603.html', headers=headers)
            bs = BeautifulSoup(exercise_success_page.text, "html.parser")
            size_ = bs.find(id="num1")["value"]

            for i in range(int(size_)):
                params = {
                    'classroomId': 603,
                    'courseSetId': 42,
                    'sortRateId': i
                }

                exercise_success_page = session.get(
                    'http://www.yidiankai.net/index/exam_ajax/get_lesson_sort_one.html', headers=headers, params=params)

                jsonstr = exercise_success_page.json()

                if jsonstr['status']:
                    data_ = jsonstr['data']

                    stem_ = data_['stem']  # 题目
                    metas_ = data_['metas']  # 选项
                    answer_ = data_['answer']  # 答案
                    analysis_ = data_['analysis']  # 答案解析

                    switch = {
                        '0': 'A',
                        '1': 'B',
                        '2': 'C',
                        '3': 'D',
                        '4': 'E',
                        '5': 'F',
                        '6': 'G'
                    }

                    loads = json.loads(metas_)
                    pattern = r'[A-Z]|、'

                    # 给选项加上A、B、C标识
                    for index in range(0, len(loads)):
                        if not re.search(pattern, loads[index]):
                            loads[index] = switch.get(str(index)) + '、' + loads[index]

                    strs = '第{0}题：{1}\n{2}\n答案：{3}'.format((i + 1), stem_,
                                                           '\n'.join(loads),
                                                           switch.get(answer_))

                    # 判断是否有答案解析
                    if len(analysis_) > 0:
                        strs += '\n答案解析：' + analysis_ + '\n\n'
                    else:
                        strs += '\n\n'

                    print(i + 1)

                    # 将字符串写入文件中
                    with open('C:\\Users\limuyi\Desktop\课后习题.txt', 'a', encoding='utf-8') as f:  # 设置文件对象
                        f.write(strs)

    except Exception as e:
        print(e)
        # 错误结束程序
        exit(0)


'''
    入口函数
'''
if __name__ == '__main__':
    remote()
